# -*- coding: utf-8 -*-
from django.shortcuts import render
from report.models import Trade, Product, Report, Institution,Frequency,Author
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.http import JsonResponse
from django.forms import  model_to_dict

def index(request):
    products = Product.objects.all()
    hots = Report.objects.all().order_by('download_count')[0:6]

    institutions = Institution.objects.all()
    frequencys=Frequency.objects.all()
    trades = Trade.objects.all()

    context = {"trades": trades, "products": products, 'hots': hots,"institutions":institutions,"frequencys":frequencys,"trades":trades}
    return render(request, "frontend/index.html", context)


def products_reports_list(request, products):
    """某一品种的研报"""
    report_list = Report.objects.filter(products_id=products)

    paginator = Paginator(report_list, 25)  # Show 25 contacts per page

    page = request.GET.get('page')
    try:
        reports = paginator.page(page)
    except PageNotAnInteger:
        # If page is not an integer, deliver first page.
        reports = paginator.page(1)
    except EmptyPage:
        # If page is out of range (e.g. 9999), deliver last page of results.
        reports = paginator.page(paginator.num_pages)

    trades = Trade.objects.all()
    products = Product.objects.all()
    hots = Report.objects.all().order_by('download_count')[0:6]
    context = {"trades": trades, "products": products, 'hots': hots, 'reports': reports}
    return render(request, 'frontend/products_reports_list.html', context)


def trade_reports_list(request, trade):
    report_list = Report.objects.filter(trade_id=trade)
    paginator = Paginator(report_list, 25)  # Show 25 contacts per page
    page = request.GET.get('page')
    try:
        reports = paginator.page(page)
    except PageNotAnInteger:
        # If page is not an integer, deliver first page.
        reports = paginator.page(1)
    except EmptyPage:
        # If page is out of range (e.g. 9999), deliver last page of results.
        reports = paginator.page(paginator.num_pages)

    trade = Trade.objects.get(code=trade)
    trades = Trade.objects.all()
    products = Product.objects.filter(trade=trade)
    hots = Report.objects.all().order_by('download_count')[0:6]
    context = {"trades": trades, "trade": trade, "products": products, 'hots': hots, 'reports': reports}
    return render(request, 'frontend/trade_reports_list.html', context)


def report_detail(request, pk):
    report = Report.objects.get(pk=pk)

    trades = Trade.objects.all()
    products = Product.objects.all()
    hots = Report.objects.all().order_by('download_count')[0:6]
    context = {"trades": trades, "products": products, 'hots': hots, "report": report}
    return render(request, 'frontend/report_detail.html', context)


def report_search_api(request):
    title = request.GET.get("title")
    author=request.GET.get("author")
    trade = request.GET.get("trade")
    trades = Trade.objects.all()
    product = request.GET.get("product")
    frequency = request.GET.get("frequency")
    institution=request.GET.get("institution")
    products = Product.objects.all()


    qs = Report.objects.all()
    if title:
        qs = qs.filter(name__contains=title)
    if trade:
        qs = qs.filter(trade_id=trade)
    if product:
         qs = qs.filter(products_id=product)
    if institution:
         qs = qs.filter(institution_id=institution)
    if frequency:
         qs = qs.filter(frequency_id=frequency)
    if author:
        inner_qs=Author.objects.filter(name__contains=author)
        qs=qs.filter(authors__in=inner_qs)

    paginator = Paginator(qs, 25)  # Show 25 contacts per page

    page = request.GET.get('page')
    if not page:
        page = 1

    try:
        reports = paginator.page(page)
    except PageNotAnInteger:
        # If page is not an integer, deliver first page.
        reports = paginator.page(1)
    except EmptyPage:
        # If page is out of range (e.g. 9999), deliver last page of results.
        reports = paginator.page(paginator.num_pages)

    object_list=[]
    for item in reports.object_list:

        dd=model_to_dict(item)
        dd["report_download"]=None
        authors=[]
        for aa in item.authors.all():
            authors.append(model_to_dict(aa))
        dd["authors"]=authors


        dd["products"] = model_to_dict(item.products)
        dd["exchange"] = model_to_dict(item.exchange)
        dd["trade"] = model_to_dict(item.trade)
        if item and item.costomize_category:
            dd["costomize_category"] = model_to_dict(item.costomize_category)
        dd["frequency"] = model_to_dict(item.frequency)
        dd["institution"] = model_to_dict(item.institution)

        object_list.append(dd)

    data={"status_code":200,"data":{"items":object_list,"current_page":page,"total_pages":paginator.num_pages}}
    return JsonResponse(data=data)

def report_search(request):
    title = request.GET.get("title")
    trade = request.GET.get("trade")

    product = request.GET.get("product")
    frequency = request.GET.get("frequency")
    institution=request.GET.get("institution")
    trades = Trade.objects.all()
    context = {"trade":trade, "product":product, "institution":institution,"trades":trades}
    return render(request, 'frontend/search_reports_list.html', context)

def report_search_metadata_api(request):
    trades = Trade.objects.all()
    products = Product.objects.all()
    institutions = Institution.objects.all()
    frequencys=Frequency.objects.all()
    tradeslist=[]
    for item in trades:
        tradeslist.append(model_to_dict(item))
    productslist=[]
    for item in products:
        productslist.append(model_to_dict(item))
    frequencyslist=[]
    for item in frequencys:
        frequencyslist.append(model_to_dict(item))

    institutionslist=[]
    for item in institutions:

        institutionslist.append(model_to_dict(item))


    data = {"status_code": 200, "data": {"trades": tradeslist, "products": productslist, "institutions": institutionslist,"frequencys":frequencyslist}}
    return JsonResponse(data=data)